import json
import os
from flask import request, jsonify
from src.api.controllers.tool_controller import ToolController
from src.api.controllers.watermark_controller import WatermarkController
from src.api.controllers.text_editor_controller import TextEditorController
from src.modules.whoosh_processor import Util
from src.utils.logger import log_error, log_info

def register_upload_routes(bp):
    controller = ToolController()
    watermark_controller = WatermarkController()
    text_editor_controller = TextEditorController()
    
    @bp.route('/tools/audio', methods=['POST'])
    def upload_audio():
        """处理音频文件上传请求"""
        # 检查请求中是否有文件
        if 'audio_file' not in request.files:
            return jsonify({"success": False, "message": "未提供音频文件"}), 400
        
        audio_file = request.files['audio_file']
        subtitle_file = request.files['subtitle_file'] if 'subtitle_file' in request.files else None
        
        group_id = request.form.get('group_id')
        # if not group_id:
            # return jsonify({"success": False, "message": "未提供组ID"})

        # 获取目标目录（如果提供）
        target_directory = request.form.get('directory', None)
        
        meta_data = request.form.get('meta_data', None)
        order = request.form.get('order', 0)
        
        log_info(f"接收到文件上传请求: 文件名={audio_file.filename}, 组ID={group_id}, 目录={target_directory}, 顺序={order}")        
        if subtitle_file:
            log_info(f"接收到字幕文件: {subtitle_file.filename}")
        # 处理文件上传
        result = controller.upload_audio(audio_file, group_id, order, subtitle_file, target_directory, meta_data)
        return jsonify(result)
    
    @bp.route('/tools/video', methods=['POST'])
    def upload_video():
        """处理视频文件上传请求"""
        # 检查请求中是否有文件
        if 'video_file' not in request.files:
            return jsonify({"success": False, "message": "未提供视频文件"}), 400
        
        video_file = request.files['video_file']
        
        meta_data = request.form.get('meta_data', None)
        
        # 处理文件上传
        result = controller.upload_video(
            video_file=video_file, 
            video_type=request.form.get('video_type'), 
            meta_data=meta_data
        )
        return jsonify(result)
    
    @bp.route('/tools/media/<file_id>', methods=['DELETE'])    
    def delete_media(file_id):
        """处理媒体文件删除请求"""
        if not file_id:
            return jsonify({"success": False, "message": "未提供文件ID"}), 400
        
        try:
            result = controller.delete_media(file_id)
            return jsonify(result)
        except Exception as e:
            return jsonify({"success": False, "message": str(e)}), 500

    @bp.route('/tools/set_default_video', methods=['POST'])
    def set_default_video():
        video_id = request.json.get('video_id')
        video_type = request.json.get('video_type')
        log_info(f"设置默认视频: video_id={video_id}, video_type={video_type}")
        if not video_id or not video_type:
            return jsonify({"success": False, "message": "未提供视频ID或视频类型"}), 400
        try:
            result = controller.set_default_video(video_id, video_type)
            return jsonify(result)
        except Exception as e:
            return jsonify({"success": False, "message": str(e)}), 500
        
    @bp.route('/tools/burn_subtitle', methods=['POST'])
    def burn_subtitle():
        """将SRT字幕文件烧录到视频文件中"""
        data = request.json
        
        if not data:
            return jsonify({"success": False, "message": "请提供请求数据"}), 400
        
        video_path = data.get('video_path')
        subtitle_path = data.get('subtitle_path')
        
        if not video_path or not subtitle_path:
            return jsonify({
                "success": False, 
                "message": "必须提供视频路径和字幕路径"
            }), 400
        
        # 检查文件是否存在
        if not os.path.exists(video_path):
            return jsonify({
                "success": False, 
                "message": f"视频文件不存在: {video_path}"
            }), 404
        
        if not os.path.exists(subtitle_path):
            return jsonify({
                "success": False, 
                "message": f"字幕文件不存在: {subtitle_path}"
            }), 404
        
        # 提取其他参数
        output_path = data.get('output_path')
        
        # 创建字幕烧录器
        result = controller.burn_subtitles(
            video_path=video_path,
            subtitle_path=subtitle_path,
            output_path=output_path,
        )
        # 返回结果
        if result["success"]:
            return jsonify(result)
        else:
            return jsonify(result), 500
        
    @bp.route('/tools/subtitle', methods=['POST'])
    def upload_subtitle():
        """处理字幕文件上传请求"""
        if 'subtitle_file' not in request.files:
            return {"success": False, "message": "未提供字幕文件"}, 400
        
        subtitle_file = request.files['subtitle_file']
        # 处理文件上传
        try:
            result = controller.upload_subtitle(subtitle_file)
            return {"success": True, "message": "字幕上传成功", 
                    "subtitle_path": result,
                    "data": result}, 200
        except Exception as e:
            log_error(f"上传字幕时出错: {e}")
            return {"success": False, "message": str(e)}, 500
    
    @bp.route('/tools/image_watermark', methods=['POST'])
    def add_floating_image_watermark():
        """处理添加浮动图片水印的请求"""
        video_folder = request.form.get('video_folder')
        image_file = request.files['watermark_image']
        
        # 参数验证
        if not all([video_folder, image_file]):
            return jsonify({
                "success": False, 
                "message": "缺少必需参数: video_path, image_file"
            }), 400
            
        try:
            # 添加浮动图片水印
            result = watermark_controller.add_floating_image_watermark(
                video_folder=video_folder,
                image_file=image_file,
            )
            # 返回结果
            return {"success": True, "message": "水印添加成功", "data": result}, 200
        except Exception as e:
            log_info(f"添加浮动图片水印时出错: {e}")
            return {"success": False, "message": str(e)}, 500
        
    @bp.route('/tools/subtitle_videos_mappings', methods=['PUT'])
    def update_subtitle_videos_mappings():
        """更新字幕与视频的映射关系"""
        data = request.json
        
        mappings = data.get('mappings', [])
        if not mappings:
            return {"success": False, "message": "必须提供映射列表"}, 400
        try:
            controller.update_subtitle_videos_mappings(mappings)
            return {"success": True, "message": "映射关系更新成功"}, 200
        except Exception as e:
            return {"success": False, "message": str(e)}, 500
        
        
    @bp.route('/tools/subtitle', methods=['GET'])
    def get_subtitle_list():
        """获取字幕列表"""
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        query = request.args.get('query', '')
        try:
            data = controller.get_subtitle_list(page=page, page_size=page_size, query=query)
            return {"success": True, "data": data, "message": "字幕列表获取成功"}, 200
        except Exception as e:
            return jsonify({"success": False, "message": str(e)}), 500
        
    @bp.route('/tools/media/<id>', methods=['GET'])
    def get_media_by_id(id):
        """根据ID获取媒体文件信息"""
        if not id:
            return jsonify({"success": False, "message": "未提供文件ID"}), 400
        
        try:
            media_info = controller.get_media_by_id(id)
            return jsonify({"success": True, "data": media_info}), 200
        except Exception as e:
            log_error(f"获取媒体文件信息时出错: {e}")
            return jsonify({"success": False, "message": str(e)}), 500
        

    @bp.route('/tools/aligned_segments', methods=['POST'])
    def aligned_segments():
        """处理对齐片段的请求"""
        data = request.json
        
        if not data or 'words' not in data or 'correct_text' not in data:
            return jsonify({"success": False, "message": "缺少必要的参数"}), 400
        
        words = data['words']
        correct_text = data['correct_text']
        
        if not isinstance(words, list) or not isinstance(correct_text, str):
            return jsonify({"success": False, "message": "参数格式错误"}), 400
        
        try:
            aligned_segments = controller.aligned_segments(words=words, correct_text=correct_text)
            return jsonify({"success": True, "data": aligned_segments}), 200
        except Exception as e:
            log_error(f"处理对齐片段时出错: {e}")
            return jsonify({"success": False, "message": str(e)}), 500